/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jmail;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Message;
import javax.mail.search.SearchTerm;

/**
 *
 * @author iflamed
 */
public class SubjectRegexTerm extends SearchTerm {

    private String pattern;
    /**
     * 根据提供的正则表达式字串，搜索主题
     * @param pattern the regex pattern 
     */
    public SubjectRegexTerm(String pattern) {
        this.pattern = pattern;
    }

    @Override
    public boolean match(Message msg) {
        String subj;

        try {
            subj = msg.getSubject();
        } catch (Exception e) {
            return false;
        }

        if (subj == null) {
            return false;
        }else{
            return find(pattern,subj);
        }
    }

    private boolean find(String regEx, String srcString) {
        srcString = srcString.trim();
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(srcString);

        boolean rs = m.find();

//        if (rs) {
//            subject = new String[m.groupCount()];
//            for (int i = 1; i <= m.groupCount(); i++) {
//                subject[i-1] = m.group(i);
//            }
//        }
        return rs;
    }
    
    /**
     * Equality comparison.
     */
    @Override
    public boolean equals(Object obj) {
	if (!(obj instanceof SubjectRegexTerm))
	    return false;
	return super.equals(obj);
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 29 * hash + (this.pattern != null ? this.pattern.hashCode() : 0);
        return hash;
    }
}
